import time, threading
import tkinter as tk
import psutil


class Win(tk.Tk):
    def __init__(self):
        super().__init__()
        self.background_color='#000000'
        self.resizable(False,False)
        self.title('网速')
        self.overrideredirect(True) # 不显示标题栏
        self.wm_attributes("-alpha", 0.7)      # 透明度
        self.wm_attributes("-topmost", True)  # 永远处于顶层
        self.up_var = tk.StringVar()
        self.down_var = tk.StringVar()
        self.up_speed = tk.Label(self,textvariable=self.up_var)
        self.down_speed = tk.Label(self,textvariable=self.down_var)
        self.up_speed.pack()
        self.down_speed.pack()

        # 设置背景颜色
        self['bg']=self.background_color
        self.up_speed['bg'] = self.background_color
        self.up_speed['fg'] = 'white'
        self.down_speed['bg'] = self.background_color
        self.down_speed['fg'] = 'white'

        self.bind('<ButtonPress-1>', self.click) # 鼠标左键点击
        self.bind('<B1-Motion>', self.move) # 鼠标左键移动
        self.bind('<ButtonPress-3>', self.popup_menu) # 右键菜单

        thread = threading.Thread(target=self.get_speed)
        thread.setDaemon(True)
        thread.start()

    def click(self, event):
        x,y = event.x_root, event.y_root # 得到点击位置的xy坐标
        x1,y1 = self.winfo_x(), self.winfo_y() # 得到组件左上角的xy坐标
        self.off_x = x-x1 #计算点击位置与左上角的差值，为后面移动时，鼠标还是显示在点击组件的那个位置
        self.off_y = y-y1
    
    def move(self, event):
        # 鼠标从原来点击的位置移动到新位置的xy距离
        x = event.x_root
        y = event.y_root

        self.geometry(f'+{x-self.off_x}+{y-self.off_y}')

    def popup_menu(self,event):
        menu = tk.Menu(self,tearoff=0)
        menu.add_command(label='退出',command=self.quit)
        menu.post(event.x_root, event.y_root)

    def get_speed(self):
        speed_up=[0,'KB/s'] # 上传 下载 单位
        speed_down=[0,'KB/s'] # 上传 下载 单位
        while True:
            allif = psutil.net_io_counters(pernic=True)
            WIFI = allif.get('WLAN')
            l_send= WIFI.bytes_sent
            l_recv= WIFI.bytes_recv

            time.sleep(1)

            allif = psutil.net_io_counters(pernic=True)
            WIFI = allif.get('WLAN')
            speed_up[0]= WIFI.bytes_sent - l_send
            speed_down[0]= WIFI.bytes_recv - l_recv
            
            up = speed_up[0]/1024 # KB
            down = speed_down[0]/1024 # KB
            if up >= 1024:
                up = up/1024
                speed_up[1] = 'MB/s'
            else:
                speed_up[1] = 'KB/s'
            
            if down >= 1024:
                down = down/1024
                speed_down[1] = 'MB/s'
            else:
                speed_down[1] = 'KB/s'

            self.up_var.set('上传 %.2f %s' % (up,speed_up[1]) )
            self.down_var.set('下载 %.2f %s' % (down,speed_down[1]) )
            psutil.disk_io_counters.cache_clear()


app = Win()
app.mainloop()